package com.zhangxiaofanfan.hotcode.second;


import java.util.ArrayList;
import java.util.List;

/**
 * TODO
 *
 * @author zhangxiaofanfan
 * @date 2024-06-26 20:33:33
 */
public class HotCode059 {
    public static void main(String[] args) {
        HotCode059 hotCode059 = new HotCode059();
        System.out.println(hotCode059.generateParenthesis(3));
    }

    private List<String> result = new ArrayList<>();
    private String[] strs = {"(", ")"};
    public List<String> generateParenthesis(int n) {
        if (n <= 0) {
            return result;
        }
        bfs(new StringBuffer(), 0, n);
        return result;
    }

    public void bfs(StringBuffer stringBuffer, int prefixCount, int n) {
        if (stringBuffer.length() >= n * 2) {
            result.add(stringBuffer.toString());
        }
        if (prefixCount < n) {
            stringBuffer.append(strs[0]);
            bfs(stringBuffer, prefixCount + 1, n);
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        }
        if (stringBuffer.length() < prefixCount * 2) {
            stringBuffer.append(strs[1]);
            bfs(stringBuffer, prefixCount, n);
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        }
    }
}
